/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

public class XMLProperties {
	private static final Log log = LogFactory.getLog(XMLProperties.class);

	/*
	 * 文件本身
	 */
	public File file;

	public Document document;

	/*
	 * 为减少开支，使用属性缓存，每次获得一个属性后即存入缓存
	 */
	private Map<String, String> propertyCache = new HashMap<String, String>();

	public XMLProperties() {
	}

	/**
	 * 根据文件名构造dom文档
	 * 
	 * @param fileName
	 *            要求使用文件名全路径
	 * @throws IOException
	 */
	public XMLProperties(String fileName) throws IOException {
		
		this(new File(fileName));
	}

	/**
	 * 根据输入流构造dom文档
	 * 
	 * @param in
	 * @throws IOException
	 */
	public XMLProperties(InputStream in) throws IOException {
		Reader reader = new BufferedReader(new InputStreamReader(in));
		buildDoc(reader);
	}

	/**
	 * 根据文件对象构造dom文档
	 * 
	 * @param file
	 * @throws IOException
	 */
	public XMLProperties(File file) throws IOException {
		this.file = file;
//		log.debug(" XMLProperties file ="+file.getAbsolutePath());
		if (!file.exists()) {
			throw new FileNotFoundException("当前EDI项目文件未找到: " + file.getName());
		}

		if (!file.canRead()) {
			throw new IOException("当前EDI项目文件不可读: " + file.getName());
		}
//		log.debug(" XMLProperties file exit");
		FileReader reader = new FileReader(file);
		buildDoc(reader);
//		log.debug(" buildDoc complete");
	}

	private void buildDoc(Reader in) throws IOException {
		try {
//			log.debug(" enter buildDoc");
			SAXReader xmlReader = new SAXReader();
			xmlReader.setEncoding("UTF-8");
			document = xmlReader.read(in);
//			log.debug(" end buildDoc");
		} catch (Exception e) {
			// Log.error("Error reading XML properties", e);
			e.printStackTrace();
			throw new IOException(e.getMessage());
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}
}
